﻿// 返回上一页并刷新
// location.href = document.referrer

// 获取url参数
var getRequest = function (name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return decodeURI(r[2]);
    }
    return null;
}

// 获取设备宽度和高度
var getDeviceWidthHeight = function () {
    return {
        width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
        height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
    }
}

// 时间转换
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
var date = new Date().Format("yyyy-MM-dd");
var datetime = new Date().Format("yyyy-MM-dd hh:mm:ss");

// 手机号验证
var checkPhone = function (num) {
    var myreg = /^[1][3456789][0-9]{9}$/;
    if (!myreg.test(num)) {
        return false;
    } else {
        return true;
    }
}

// 身份证号验证
var checkCode = function (val) {
    var p = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
    var code = val.substring(17);
    if (p.test(val)) {
        var sum = 0;
        for (var i = 0; i < 17; i++) {
            sum += val[i] * factor[i];
        }
        if (parity[sum % 11] == code.toUpperCase()) {
            return true;
        }
    }
    return false;
}

// 网址验证
var checkUrl = function (url) {
    var reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/;
    if (!reg.test(url)) {
        return false;
    } else {
        return true;
    }
}

// 统一社会信用代码验证
var checkLicense = function (code) {
    var result = true
    var reg = /^([159Y]{1})([1239]{1})([0-9]{6})([0-9ABCDEFGHJKLMNPQRTUWXY]{9})([0-9ABCDEFGHJKLMNPQRTUWXY]{1})$/;
    if (!reg.test(code)) {
        result = false
    }
    //不用I、O、S、V、Z
    var str = '0123456789ABCDEFGHJKLMNPQRTUWXY';
    var ws = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];
    var codeArr = []
    var sum = 0
    codeArr[0] = code.substr(0, code.length - 1);
    codeArr[1] = code.substr(code.length - 1, code.length);
    for (var i = 0; i < codeArr[0].length; i++) {
        var Ancode = codeArr[0].charAt(i);
        var Ancodevalue = str.indexOf(Ancode);
        sum += Ancodevalue * ws[i];
    }
    var indexOfCode18 = 31 - (sum % 31);
    var code18 = str.charAt(indexOfCode18);
    if (code18 != codeArr[1]) {
        result = false
    }
    return result;
}

// 复制信息到剪贴板
var copyStr = function (str) {
    var createInput = document.createElement('input');
    createInput.setAttribute('value', str);
    document.body.appendChild(createInput);
    createInput.select();
    document.execCommand('copy');
    document.body.removeChild(createInput);
    alert('已复制【' + str + '】到剪贴板')
}

// 获取多行信息
var getMoreLine = function (arg) {
    var array = [];
    $.each($('#' + arg + ' input:checkbox'), function () {
        if (this.checked) {
            var a = $(this).parent().parent().attr('data-id');
            array.push(a);
        }
    });
    return array;
}

// 表单空值提示
var nullAlert = function (arg) {
    var result = true
    $('.' + arg).each(function () {
        if ($(this).val() == '') {
            var text = $(this).parent().prev().text()
            layer.alert(text + '不能为空')
            result = false
            return result;
        }
    })
    return result;
}

// 表单赋值
var setData = function (data) {
    for (var key in data) {
        $("#" + key).val((data[key] == undefined ? '' : data[key]))
    }
}

// 拼接data
var getData = function (arg) {
    var data = {};
    $("." + arg).each(function () {
        var a = $(this).attr("id");
        var b = $(this).val();
        eval('data.' + a + '="' + b + '"');
    })
    return data;
}

// 生成随机整数
var randomInteger = function (min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}

// 数组去重
var arrayRemoveRepeat = function (arr) {
    return arr.filter(function (item, index, self) {
        return self.indexOf(item) === index;
    });
}

// 生成范围内不重复随机数字
var randNum = function (min, max, num) {
    if (num > max - min) {
        console.error("范围太小");
        return false;
    }
    var range = max - min;
    var minV = min + 1;
    var arr = [];
    var tmp = "";

    function GenerateANum(i) {
        for (i; i < num; i++) {
            var rand = Math.random();
            tmp = Math.floor(rand * range + minV);
            if (arr.indexOf(tmp) == -1) {
                arr.push(tmp);
            } else {
                GenerateANum(i);
                break;
            }
        }
    }
    GenerateANum(0);
    return arr;
}

// 加载lineLoad
var lineLoad = function () {
    var html = ""
    html += '<div id="lineLoadBox">'
    html += '    <div class="loader">'
    html += '        <div class="line lineOne"></div>'
    html += '        <div class="line lineTwo"></div>'
    html += '        <div class="line lineThree"></div>'
    html += '    </div>'
    html += '</div>'
    $("body").append(html)
}

// 加载circleLoad
var circleLoad = function (str) {
    var html = ""
    var text = str == undefined ? "加载中" : str
    html += '<div id="circleLoadBox">'
    html += '    <div class="circleLoad"></div>'
    html += '    <div class="circleLoadText">' + text + '</div>'
    html += '</div>'
    $("body").append(html)
}

// 移除load
var removeLoad = function () {
    $("#lineLoadBox, #circleLoadBox").remove()
}

// 判断手机系统
var checkMobileSystem = function () {
    var userAgent = navigator.userAgent
    var isAndroid = userAgent.indexOf('Android') > -1 || userAgent.indexOf('Adr') > -1
    var isIos = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
    if (isAndroid) {
        return 'isAndroid'
    } else if (isIos) {
        return 'isIos'
    }
}

// 判断设备
var checkDevice = function () {
    var flag = false
    var userAgentInfo = navigator.userAgent
    var mobileAgents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod']
    for (var v = 0; v < mobileAgents.length; v++) {
        if (userAgentInfo.indexOf(mobileAgents[v]) > 0) {
            flag = true
            break;
        }
    }
    return flag;
}

// location.replace兼容版
var locationReplace = function (url) {
    if (history.replaceState) {
        history.replaceState(null, document.title, url)
        history.go(0)
    } else {
        location.replace(url)
    }
}

// 滚动加载数据
function loadData() {
    $('#listIn').html('')
    $('.list-donetip, .J_InfiniteScrollTag, .list-loading').remove()
    var page = 1
    var pageSize = 10
    $('#listOut').infiniteScroll({
        pageSize: pageSize,
        initLoad: true,
        loadingHtml: '<img src="icon/loading.gif"/>',
        loadListFn: function () {
            var def = $.Deferred()
            $.post('url', {
                page: page,
                limit: pageSize
            }, function (ret) {
                var html = ''
                var res = ret.data
                if (ret.count == 0) {
                    $('.list-loading').hide()
                    $('#listIn').append('<h1 style="text-align:center;line-height:40px;color:#777;">暂无数据</h1>')
                } else {
                    for (var i = 0; i < res.length; i++) {
                        html += ''
                    }
                    $('#listIn').append(html)
                    def.resolve(ret.data)
                    ++page
                }
            });
            return def.promise()
        }
    });
}